package com.example.shop.rabbitmq.component;


import com.rabbitmq.client.Channel;

import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MerchantMessageComponent {

    /**
     * 商家的消息交换机
     */
    public static final String MSG_EXCHANGE = "merchant.message.topic";
    /**
     * 商家消息队列前缀
     */
    public static final String QUEUE_PRE = "merchant_message_";

    /**
     * 声明创建一个主题交换机
     * @return 返回一个主题交换机
     */
    @Bean("merchantMessageExchange")
    public TopicExchange messageExchange(){
        return ExchangeBuilder.topicExchange(MSG_EXCHANGE)
                .durable(true)
                .build();
    }

    /**
     * 声明创建一个队列，并与商家的消息交换机进行绑定
     * 该队列存放ChatMessage对象
     * @param channel mq通道
     * @param merchantId 商家id
     * @return 返回操作结果，如果为true，代表成功，返回代表失败
     */
    public static Boolean queueDeclareAndBind(Channel channel, Long merchantId){
        String queueName = QUEUE_PRE+merchantId;
        Map<String,Object> queueProperties=new HashMap();
        queueProperties.put("x-queue-mode", "lazy");
        try {
            //声明一个队列，队列不持久性，消费者不独占队列，不自动删除
            channel.queueDeclare(queueName, true, false, false, queueProperties);
            //路由键为商家id，即队列名
            String routingKey = String.valueOf(merchantId);
            //将该声明的队列与该交换机绑定
            channel.queueBind(queueName,MSG_EXCHANGE,routingKey);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
